package ld.utils;

import java.sql.*;

/**
 * Created by David on 2017/7/30 030.
 */
public class MysqlUtils {
    private static final String url = "jdbc:mysql://localhost/student";
    private static final String name = "com.mysql.jdbc.Driver";
    private static final String user = "root";
    private static final String password = "";

    private static Connection conn = null;


    private static void connect() throws Exception{
        Class.forName(name); //指定连接类型
        conn = DriverManager.getConnection(url, user, password); //获取连接
        System.out.println("connected");
    }

    public static ResultSet querySql(String sql){
        try{
            if (conn == null) connect();
            //conn.close();
            return conn.prepareStatement(sql).executeQuery();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String getPassword(String email){
        try {
            String sql = "select password from user where email='" + email +  "'";
            ResultSet ret = MysqlUtils.querySql(sql);
            if (ret.next()){
                return ret.getString(1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    public static ResultSet getUserInfo(String email){
        try {
            String sql = "select username,email_active,area,sex from user where email='" + email +  "'";
            ResultSet ret = MysqlUtils.querySql(sql);
            if (ret.next()){
                return ret;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    public static boolean checkPassword(String inputPassword, String savedPassword){
        try{
            ResultSet ret = MysqlUtils.querySql("select password('" + inputPassword + "')");
            if (ret.next()){
                if (ret.getString(1).equals(savedPassword)){
                    return true;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public static boolean userRegister(String email, String psw){
        try{
            String sql = "insert into user (email,username,password) values ('" + email + "','" + email + "',password('" + psw + "'))";
            int rowEffect = conn.prepareStatement(sql).executeUpdate();
            System.out.println(rowEffect);
            if (rowEffect != 0){
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

}
